<template>
    <div>
        <global-tables
            @handleAllSelect="handleAllSelect"
            @changePage="handleChangePage"
            :list="list"
            :total="total"
            :loading="loading"
            :columns="columns"
            :current="search.pageindex"
        >
            <Form :model="search" :label-width="80">
                <div class="table-top-wrap">
                    <div>
                        <div>
                            <Button v-if="isAddBtn" class="features-btn" @click="handleBtnClick(null,'add')">
                                <Icon type="md-add" size="18" />新建
                            </Button>
                            <Button v-if="isDelete" class="features-btn btn-auto-m" @click="handleBtnClick(null,'delete')">
                                <Icon type="md-trash" size="17" />删除
                            </Button>
                        </div>
                    </div>
                    <div class="table-top-wrap-bottom">
                        <Select v-model="search.status" style="width:120px;margin:0 px" placeholder="状态" @on-change="handleState">
                            <Option value="-1">全部</Option>
                            <Option value="1">待审核</Option>
                            <Option value="2">审核中</Option>
                            <Option value="3">已审结</Option>
                            <Option value="4">已完成</Option>
                            <Option value="5">已确认</Option>
                        </Select>
                        <Select v-model="search.type" style="width:100px;margin:0 10px" placeholder="类别" @on-change="handleState">
                            <Option value="-1">全部</Option>
                            <Option value="2">采购入库</Option>
                            <Option value="1">按店打包</Option>
                        </Select>
                        <div>
                            <input type="text" class="style-input" @keyup.enter="handleSearch" v-model="search.keyword" placeholder="请输入采购单名称" />
                            <i-input style="display:none"></i-input>
                        </div>
                        <div>
                            <Button icon="ios-search" @click="handleSearch" class="search-btn">搜索</Button>
                        </div>
                    </div>
                </div>
            </Form>
        </global-tables>
        <Modal :mask-closable="false" v-model="isModal" :title="ModalTitle" :width="modalWidth">
            <div v-if="isModal">
                <div v-if="!isView">
                    <Form ref="formItem" :model="formItem" :rules="ruleValidate" :label-width="100">
                        <Row>
                            <i-col :lg="{ span: 12}">
                                <FormItem label="标题" prop="Title">
                                    <i-input v-model="formItem.Title" placeholder="请输入标题"></i-input>
                                </FormItem>
                            </i-col>
                        </Row>
                        <Row>
                            <i-col :lg="{ span: 12}">
                                <FormItem label="所属供应商" prop="SupplierID">
                                    <AsyncSelect
                                        :url="'Supplier/GetAllGridJson'"
                                        :value="'SupplierID'"
                                        :currentModel="formItem.SupplierID"
                                        @setDictionaries="setDictionaries"
                                    ></AsyncSelect>
                                </FormItem>
                            </i-col>
                        </Row>
                        <Row>
                            <i-col :lg="{ span: 12}">
                                <FormItem label="采购单类别" prop="OrderType">
                                    <RadioGroup v-model="formItem.OrderType">
                                        <Radio label="1">按店打包</Radio>
                                        <Radio label="2">采购入库</Radio>
                                    </RadioGroup>
                                </FormItem>
                            </i-col>
                        </Row>
                        <Row>
                            <i-col :lg="{ span: 12}">
                                <FormItem label="要求到货日期" prop="ArriveTime">
                                    <DatePicker type="date" v-model="formItem.ArriveTime" placeholder="请选择日期" style="width: 180px"></DatePicker>
                                </FormItem>
                            </i-col>
                        </Row>
                        <Row>
                            <i-col :lg="{ span: 24}">
                                <FormItem label="描述" prop="Remark">
                                    <i-input type="textarea" v-model="formItem.Remark" placeholder="请输入备注"></i-input>
                                </FormItem>
                            </i-col>
                        </Row>
                    </Form>
                </div>
                <div v-else>
                    <div class="view-top">
                        <Card :dis-hover="true">
                            <p slot="title">采购单信息</p>
                            <Row>
                                <i-col :lg="{ span: 5}">
                                    <span class="view-top-lable">标题 :</span>
                                    <span>{{formItem.Title}}</span>
                                </i-col>
                                <i-col :lg="{ span: 8}">
                                    <span class="view-top-lable">所属供应商 :</span>
                                    <span>{{formItem.SupplierName}}</span>
                                </i-col>
                                <i-col :lg="{ span: 5}">
                                    <span class="view-top-lable">采购单类别 :</span>
                                    <span>{{formItem.OrderType == 1 ?'按店打包' : '采购入库' }}</span>
                                </i-col>
                                <i-col :lg="{ span: 5}">
                                    <span class="view-top-lable">要求到货日期 :</span>
                                    <span>{{formItem.ArriveTime}}</span>
                                </i-col>
                                <i-col :lg="{ span: 24}">
                                    <span class="view-top-lable">描述 :</span>
                                    <span>{{formItem.Remark}}</span>
                                </i-col>
                            </Row>
                        </Card>
                    </div>
                    <div class="view-bottom">
                        <Card :dis-hover="true">
                            <p slot="title">明细信息</p>
                            <Table :loading="loading" max-height="400" :columns="detailColumns" :data="detailList"></Table>
                        </Card>
                    </div>
                </div>
            </div>
            <div slot="footer">
                <Button size="large" @click="handleClose">取消</Button>
                <Button type="primary" size="large" @click="handleSubmit('formItem')" v-if="!isView">确定</Button>
            </div>
        </Modal>
        <Approval
            @setApproval="setApproval"
            :directory="{directory:'OrgPath'}"
            :isApproval="isApproval"
            :groupid="4"
            :check="1"
            v-if="isApproval"
            :id="itemId"
            :ApprovalTitle="'提交审批'"
            :label="ApprovalLabel"
        ></Approval>
    </div>
</template>

<script>
/**
 *  采购单列表
 */
import { cyclicRouting, getdate } from '@/util';
import { getModulePermission } from '@/api/user';
import Api from './service';
import GlobalTables from '@/components/GlobalTables';
import AsyncSelect from '@/components/AsyncSelect';
import Approval from '@/components/Approval';

export default {
    name: 'PurchaseList',
    components: {
        GlobalTables,
        AsyncSelect,
        Approval
    },
    data() {
        const validatorSupplierID = (rule, value, callback) => {
            setTimeout(() => {
                if (this.formItem.SupplierID == '' || !this.formItem.SupplierID) {
                    callback(new Error('请选择所属供应商'));
                } else {
                    callback();
                }
            }, 100);
        };
        return {
            list: [],
            detailColumns: [
                {
                    title: '商品名称',
                    key: 'PName'
                },
                {
                    title: '规格名称',
                    width: 300,
                    key: 'PSName'
                },
                {
                    title: '数量',
                    key: 'Count'
                },
                {
                    title: '成本',
                    key: 'Cost'
                },
                {
                    title: '小计',
                    key: 'SubTotal'
                }
            ],
            detailList: [],
            total: 0,
            itemId: 0,
            isView: false,
            isApproval: false,
            ApprovalLabel: '',
            loading: true,
            isDelete: false,
            isAddBtn: false,
            isModal: false,
            isDetail: false,
            allSelectArr: null,
            modalWidth: 600,
            ModalTitle: '新建采购单',
            formItem: this.initFormItem(),
            ruleValidate: {
                SupplierID: [
                    {
                        required: true,
                        validator: validatorSupplierID,
                        message: '请选择所属供应商'
                    }
                ],
                Title: [
                    {
                        required: true,
                        message: '请选择输入标题',
                        trigger: 'change'
                    }
                ],
                ArriveTime: [
                    {
                        required: true,
                        message: '请选择日期',
                        trigger: 'change',
                        pattern: /.+/
                    }
                ],
                OrderType: [
                    {
                        required: true,
                        message: '请选择所属供应商',
                        trigger: 'change'
                    }
                ]
            },
            search: {
                keyword: '',
                pageindex: 1,
                pagesize: 10,
                status: '',
                type: ''
            },
            columns: [
                {
                    type: 'selection',
                    width: 60,
                    align: 'center'
                },
                {
                    title: '标题',
                    key: 'Title'
                },
                {
                    title: '供货商',
                    width: 85,
                    render: (h, params) => {
                        return h('div', [
                            h(
                                'Poptip',
                                {
                                    props: { placement: 'bottom' }
                                },
                                [
                                    h(
                                        'span',
                                        {
                                            style: {
                                                display: 'inline-block',
                                                width: params.column._width * 0.6 + 'px',
                                                overflow: 'hidden',
                                                textOverflow: 'ellipsis',
                                                whiteSpace: 'nowrap'
                                            }
                                        },
                                        params.row.SupplierName
                                    ),
                                    h(
                                        'span',
                                        {
                                            slot: 'content',
                                            style: {
                                                whiteSpace: 'normal',
                                                wordBreak: 'break-all'
                                            }
                                        },
                                        params.row.SupplierName
                                    )
                                ]
                            )
                        ]);
                    }
                },
                {
                    title: '编号',
                    width: 75,
                    render: (h, params) => {
                        return h('div', [
                            h(
                                'Poptip',
                                {
                                    props: { placement: 'bottom' }
                                },
                                [
                                    h(
                                        'span',
                                        {
                                            style: {
                                                display: 'inline-block',
                                                width: params.column._width * 0.6 + 'px',
                                                overflow: 'hidden',
                                                textOverflow: 'ellipsis',
                                                whiteSpace: 'nowrap'
                                            }
                                        },
                                        params.row.OrderCode
                                    ),
                                    h(
                                        'span',
                                        {
                                            slot: 'content',
                                            style: {
                                                whiteSpace: 'normal',
                                                wordBreak: 'break-all'
                                            }
                                        },
                                        params.row.OrderCode
                                    )
                                ]
                            )
                        ]);
                    }
                },
                {
                    title: '金额',
                    width: 70,
                    key: 'TotalPrice'
                },
                {
                    title: '数量',
                    width: 70,
                    key: 'TotalCount'
                },
                {
                    title: '类别',
                    width: 100,
                    render: (h, params) => {
                        const { OrderType } = params.row;
                        if (OrderType == 1) {
                            return h('div', [h('span', {}), '按店打包 ']);
                        } else {
                            return h('div', [h('span', {}), '采购入库']);
                        }
                    }
                },
                {
                    title: '下单人',
                    width: 80,
                    key: 'Creator'
                },
                {
                    title: '状态',
                    width: 120,
                    render: (h, params) => {
                        const { State } = params.row;
                        if (State == 1) {
                            return h('div', [
                                h('Badge', {
                                    props: {
                                        status: 'success',
                                        text: '待审核'
                                    }
                                })
                            ]);
                        } else if (State == 2) {
                            return h('div', [
                                h('Badge', {
                                    props: {
                                        status: 'processing',
                                        text: '审核中'
                                    }
                                })
                            ]);
                        } else if (State == 3) {
                            return h('div', [
                                h('Badge', {
                                    props: {
                                        status: 'warning',
                                        text: '已审结'
                                    }
                                })
                            ]);
                        } else if (State == 4) {
                            return h('div', [
                                h('Badge', {
                                    props: {
                                        status: 'error',
                                        text: '已完成'
                                    }
                                })
                            ]);
                        } else if (State == 5) {
                            return h('div', [
                                h('Badge', {
                                    props: {
                                        status: 'error',
                                        text: '已作废'
                                    }
                                })
                            ]);
                        }
                    }
                },
                {
                    title: '到货时间',
                    width: 115,
                    render: (h, params) => {
                        return h('div', [
                            params.row.ArriveTime &&
                                h(
                                    'span',
                                    {
                                        props: {
                                            type: 'primary',
                                            size: 'small'
                                        }
                                    },
                                    getdate(new Date(params.row.ArriveTime).getTime())
                                )
                        ]);
                    }
                },
                {
                    title: '下单时间',
                    width: 115,
                    render: (h, params) => {
                        return h('div', [
                            params.row.CreateTime &&
                                h(
                                    'span',
                                    {
                                        props: {
                                            type: 'primary',
                                            size: 'small'
                                        }
                                    },
                                    getdate(new Date(params.row.CreateTime).getTime())
                                )
                        ]);
                    }
                },
                {
                    title: '操作',
                    width: 170,
                    align: 'left',
                    render: (h, params) => {
                        const { isEdit, isDetail } = this;
                        const { State } = params.row;
                        return h('div', [
                            isEdit &&
                                State == 1 &&
                                h(
                                    'Button',
                                    {
                                        props: {
                                            type: 'primary',
                                            size: 'small'
                                        },
                                        style: {
                                            background: '#5ab1ef',
                                            border: 'none',
                                            margin: '5px 2px'
                                        },
                                        on: {
                                            click: () => {
                                                this.handleBtnClick(params.row, 'edit');
                                            }
                                        }
                                    },
                                    '修改'
                                ),
                            //isEdit &&
                            // State != 0 &&
                            // h(
                            //     'Button',
                            //     {
                            //         props: {
                            //             type: 'primary',
                            //             size: 'small'
                            //         },
                            //         style: {
                            //             background: '#5ab1ef',
                            //             border: 'none',
                            //             margin: '5px 2px'
                            //         },
                            //         on: {
                            //             click: () => {
                            //                 this.handleBtnClick(params.row, 'view');
                            //             }
                            //         }
                            //     },
                            //     '查看'
                            // ),
                            isDetail &&
                                // State != 1 &&
                                h(
                                    'Button',
                                    {
                                        props: {
                                            type: 'primary',
                                            size: 'small'
                                        },
                                        style: {
                                            background: 'rgb(252, 134, 117)',
                                            border: 'none',
                                            margin: '5px 2px'
                                        },
                                        on: {
                                            click: () => {
                                                this.handleBtnClick(params.row, 'detail');
                                            }
                                        }
                                    },
                                    '明细'
                                ),
                            State == 1 &&
                                h(
                                    'Button',
                                    {
                                        props: {
                                            type: 'success',
                                            size: 'small'
                                        },
                                        style: {
                                            border: 'none',
                                            margin: '5px'
                                        },
                                        on: {
                                            click: () => {
                                                this.handleBtnClick(params.row, 'approval');
                                            }
                                        }
                                    },
                                    '审批'
                                )
                        ]);
                    }
                }
            ]
        };
    },
    methods: {
        /* 表格数据请求 */
        getTablesListData() {
            const data = this.search;
            Api.getTablesList(data).then(res => {
                this.list = res.data.rows;
                this.loading = false;
                this.total = res.data.records;
            });
        },
        //状态改变
        handleState() {
            this.getTablesListData();
        },
        /* 表格查询 */
        handleSearch() {
            this.loading = true;
            this.getTablesListData();
        },
        /* 供货商选择 */
        setDictionaries(item, value) {
            if (value == 'SupplierID') {
                this.formItem[value] = item.ID + ' ';
                this.formItem.SupplierName = item.name;
            } else {
                this.formItem.FactoryID = item.ID + '';
                this.formItem.FactoryName = item.name;
            }
        },
        /* 对话框 */
        handleBtnClick(item, type) {
            this.isView = true;
            if (type == 'edit' || type == 'add') {
                this.itemId = 0;
                this.ModalTitle = '新建采购单';
                this.modalWidth = 600;
                this.isView = false;
                this.formItem = this.initFormItem();
                if (type == 'edit') {
                    this.itemId = item.ID;
                    this.ModalTitle = '修改采购单';
                    Api.getItemInfo({
                        id: item.ID
                    }).then(res => {
                        this.itemId = item.ID;
                        this.isModal = true;
                        this.formItem = {
                            ...res.data,
                            SupplierID: res.data.SupplierID + ''
                        };
                    });
                } else {
                    this.isModal = true;
                }
            } else if (type === 'delete') {
                if (this.allSelectArr) {
                    this.$Modal.confirm({
                        title: `你确定要删除吗`,
                        onOk: () => {
                            Api.deleteItem({
                                ids: this.allSelectArr
                            }).then(res => {
                                if (res.state == 'success') {
                                    this.$Message.success(res.message);
                                    this.allSelectArr = '';
                                } else {
                                    this.$Message.error(res.message);
                                }
                                this.getTablesListData();
                            });
                        },
                        onCancel: () => {
                            this.$Message.info('取消成功');
                        }
                    });
                } else {
                    this.$Message.error('请先选择需要操作的记录');
                }
            } else if (type == 'detail') {
                this.$router.push({
                    path: `/ppurchase-list-detail/${item.ID}/${item.OrderCode}/${item.State}`
                });
            } else if (type == 'approval') {
                this.isApproval = true;
                this.ApprovalLabel = item.Title;
                this.itemId = item.ID;
            } else if (type == 'view') {
                this.itemId = item.ID;
                this.ModalTitle = '查看采购单';
                Api.getItemInfo({
                    id: item.ID
                }).then(res => {
                    this.itemId = item.ID;
                    this.isModal = true;
                    this.formItem = {
                        ...res.data,
                        SupplierID: res.data.SupplierID + ''
                    };
                    Api.getTablesListDetail({
                        oid: item.ID
                    }).then(res => {
                        this.detailList = res.data.rows;
                        this.loading = false;
                        this.isView = true;
                        this.modalWidth = 1000;
                    });
                });
            }
        },
        /* 表格分页方法 */
        handleChangePage(type, page) {
            this.loading = true;
            if (type == 'page') {
                this.search.pageindex = page;
                this.getTablesListData();
            } else {
                this.search.pagesize = page;
                this.getTablesListData();
            }
        },
        /* 复选框选中 */
        handleAllSelect(list) {
            let arr = [];
            for (let item in list) {
                arr.push(list[item].ID);
                arr.join(',');
            }
            arr = arr.join(',');
            this.allSelectArr = arr;
        },
        /* 关闭审批 */
        setApproval() {
            this.isApproval = false;
            this.getTablesListData();
        },
        /* 提交 */
        handleSubmit(name) {
            this.$refs[name].validate(valid => {
                if (valid) {
                    const data = this.formItem;
                    Api.addTablesItem(data).then(res => {
                        if (res.state == 'success') {
                            this.$Message.success('操作成功');
                            this.loading = true;
                            this.isModal = false;
                            this.getTablesListData();
                        } else {
                            this.$Message.error(res.message);
                        }
                    });
                }
            });
        },
        /* 关闭对话框 */
        handleClose() {
            this.isModal = false;
        },
        /* 表单数据 */
        initFormItem() {
            return {
                Remark: '',
                OrderType: '1'
            };
        }
    },
    mounted() {
        /* 获取菜单的id */
        cyclicRouting(JSON.parse(sessionStorage.getItem('user')).menuList, this.$route, id => {
            /* 按钮权限请求 */
            getModulePermission({
                roleid: JSON.parse(sessionStorage.getItem('user')).roleid,
                moduleid: id
            }).then(res => {
                /* 按钮权限赋值 */
                for (let item in res.data) {
                    if (res.data[item].name == 'add') {
                        this.isAddBtn = true;
                    } else if (res.data[item].name == 'delete') {
                        this.isDelete = true;
                    } else if (res.data[item].name == 'edit') {
                        this.isEdit = true;
                    } else if (res.data[item].name == 'detail') {
                        this.isDetail = true;
                    }
                }
                /* 列表请求 */
                this.getTablesListData();
            });
        });
    }
};
</script>
<style lang="less" scoped>
.view-bottom {
    margin-top: 20px;
}

.view-top-lable {
    margin-right: 10px;
}
</style>
